import { defineStore } from "pinia";
import { useRoute, useRouter } from "vue-router";

export const useTagViewStore = defineStore("tagView", () => {
  // tagView相关的数据
  const tagList = useStorage("tagList", [] as TagView[]);
  // 路由相关
  const route = useRoute();
  const router = useRouter();
  // 当前路由
  const currentRoutePath = ref("");

  // 当前tag
  const currentTag = computed(() => {
    return tagList.value.find(
      (item: TagView) => item.path === currentRoutePath.value
    );
  });

  // 清空
  const resetTagView = () => {
    tagList.value = tagList.value.filter((item: TagView) => !item.meta?.close);
    router.push("/");
  };

  // 添加一个
  const addTagView = (route: TagView) => {
    // 添加一个tagView
    if (route.meta?.hidden !== false) {
      return;
    }
    if (!hasTagView(route)) {
      if (route.meta?.close === false) {
        tagList.value.unshift(route);
      } else {
        tagList.value.push(route);
      }
    }
  };

  // 删除一个
  const delTagView = (route: TagView) => {
    // 删除一个tagView
    if (!hasTagView(route)) {
      return;
    }
    if (route.meta?.close === false) {
      return;
    }
    const findIndex = tagList.value.findIndex(
      (item: TagView) => item.path === route.path
    );
    if (findIndex === -1) {
      return;
    }

    if (route.path === currentRoutePath.value) {
      // 当前页面正在这个标签上
      const nextRoute =
        tagList.value[findIndex - 1] || tagList.value[findIndex + 1];
      if (nextRoute) {
        // 跳转路由
        router.push(nextRoute.path);
      } else {
        // 跳转路由
        router.push("/");
      }
    }
    tagList.value.splice(findIndex, 1);
  };

  // 判断是否有某一个值
  const hasTagView = (route: TagView) => {
    const result =
      tagList.value.find((item: TagView) => item.path === route.path) || null;
    if (!result) {
      return false;
    }

    return result;
  };

  // 关闭其他标签
  const delOtherTag = (route: TagView) => {
    tagList.value = tagList.value.filter(
      (item: any) => item.path === route.path || item.meta?.close === false
    );
  };

  watchEffect(() => {
    if (currentRoutePath.value !== route.path) {
      addTagView({ ...route } as TagView);
    }
    currentRoutePath.value = route.path;
  });

  return {
    tagList,
    currentTag,
    delOtherTag,
    hasTagView,
    resetTagView,
    addTagView,
    delTagView,
  };
});
